package net.wicp.tams.common.apiext;

import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.commons.collections.CollectionUtils;

/**
 * 
 * @author 偏锋书生
 *
 */
public class JmxUtil {
	/***
	 * 得到无验证的连接
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @return jmx连接
	 */
	public static JMXConnector connect(String host, int port) {
		String url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
		try {
			JMXServiceURL serviceUrl = new JMXServiceURL(url);
			JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceUrl, null);
			// MBeanServerConnection mbeanConn =
			// jmxConnector.getMBeanServerConnection();
			return jmxConnector;
		} catch (Exception e) {
			return null;
		}
	}

	public static JMXConnector connect(int port) {
		return connect("localhost", port);
	}

	/**
	 * 查询MBean
	 * 
	 * @param conn
	 *            jmx连接
	 * @param beanName
	 *            要查找到的bean名
	 * @return 要查找的MBean
	 */
	public static ObjectName queryMBean(JMXConnector conn, String beanName) {
		try {
			MBeanServerConnection mbeanConn = conn.getMBeanServerConnection();
			ObjectName queryName = new ObjectName(beanName);//"Commons:name=DuckulaControl"
			Set<ObjectName> beanSet = mbeanConn.queryNames(queryName, null);
			if (CollectionUtils.isEmpty(beanSet)) {
				return null;
			}
			return beanSet.iterator().next();
		} catch (Exception e) {
			return null;
		}
	}
}
